<template>
  <el-dialog
    title="硬件审核"
    v-model="visible"
    top="10vh"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataFormRules"
      label-position="right"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="审核" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio v-for="item in statusList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="auditRemark">
        <el-input type="textarea" v-model="dataForm.auditRemark" placeholder="请输入审核备注"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'

import { updateStatus, type ICreateOrUpdateEquipment } from '@/api/equipment'

import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  currId: {
    type: String,
    required: true,
    default: ''
  }
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const statusList = ref<Array<any>>([{
  label: '审核不通过',
  value: 0
},
{
  label: '审核通过',
  value: 1
}])

const visible = ref<boolean>(false)

const defaultForm = {
  id: '',
  auditRemark: '',
  status: 1
}

const handleClose = () => {
  dataForm.value = {
    id: '',
    auditRemark: '',
    status: 1
  }
  emit(UPDATE_MODEL_EVENT, false)
}
// 表单逻辑
const dataForm = ref<ICreateOrUpdateEquipment>({ ...defaultForm })
const dataFormRules = {
  auditRemark: [{ required: true, message: '请输入审核备注', trigger: 'blur' }],
}

watch(() => props.modelValue,
  async () => {
    visible.value = props.modelValue
    dataForm.value.id = props.currId
  }
)
const loading = ref<boolean>(false)

const dataFormRef = ref()
const updateOrCreate = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const status = dataForm.value.status
      console.log(dataForm.value);
      // return false
      const res = await updateStatus({ id: props.currId, status: status, auditRemark: dataForm.value.auditRemark })
      loading.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '创建成功' })
        emit('change')
        handleClose()
      } else {
        ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
      }
    }
  })
}
</script>
